package com.dpj.test;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

@Slf4j(topic = "c. ObjectOrientedIncrement")
public class ObjectOrientedIncrement {
    @SneakyThrows
    public static void main(String[] args) {
        Room room=new Room();

        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                //对临界区加锁
              room.increment();

            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 5000; i++) {
                //对临界区加锁
             room.decrement();

            }
        }, "t2");
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.debug("{}", room.getCount());

    }


}

class Room {
    private int count;

    public void increment() {
        synchronized (this) {
            count++;
        }
    }

    public void decrement() {
        synchronized (this) {
            count--;
        }
    }

    public int getCount(){
        return count;
    }

}
